<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showDialogTitle"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table id="margin" v-loading="loading" :data="list" border>
              <el-table-column label="序号" type="index" :index="indexMethod" width="100" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 3, 5, 7, 10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />

          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>

          </el-tab-pane>

        </el-tabs>
      </el-card>

      <!-- 弹窗 -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitBtn">确认</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
        @open="openAssignDialog"
      >
        <el-tree
          ref="tree"
          :data="permissionData"
          :props="{ label: 'name' }"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssign">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { tranListToTreeData } from '@/utils'
import { reqGetPermissionList } from '@/api/permisson'
export default {
  name: 'Setting',
  data() {
    return {
      list: [],
      total: 0, // 总条数
      page: 1,
      pagesize: 10,

      loading: false, // 页面加载效果

      showDialog: false, // 弹出框

      showTitle: '',

      companyForm: {},

      showAssignDialog: false, // 分配权限弹窗

      permissionData: [], // 存储权限数据

      roleId: '',

      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取角色数据
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      this.list = rows
      this.total = total
      this.loading = false
    },
    // newSize 几条每页
    handleSizeChange(newSize) {
      this.pagesize = newSize
      this.getRoleList()
    },
    // 第几页
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getRoleList()
    },
    // 自定义序号 顺序
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除
    async delRole(id) {
      const ress = await this.$confirm('确定删除吗?', '提示').catch(error => error)
      if (ress !== 'confirm') return
      if (this.list.length === 1 && this.page > 1) this.page--
      const res = await reqDeleteRole(id)
      this.$message.success(res.message)
      this.getRoleList()

      // this.list.forEach(async item => {
      //   return await reqDeleteRole(item.id)
      // })
    },
    // 点击新增角色按钮
    showDialogTitle() {
      this.showDialog = true // 弹出框
      this.showTitle = '新增角色'
    },
    // 弹窗 X按钮
    closeDialog() {
      this.showDialog = false // 关闭弹窗
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 添加/编辑角色
    submitBtn() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          const res = await reqUpdateRole(this.form)
          this.$message.success(res.message)
        } else {
          const res = await reqAddRole(this.form)
          this.$message.success(res.message)
        }
        this.getRoleList()
        this.closeDialog()
      })
    },
    // 点击编辑按钮回显数据
    async showEdit(id) {
      this.showTitle = '编辑角色'
      this.showDialog = true
      const res = await reqGetRoleDetail(id)
      this.form = res.data
    },
    // 获取公司信息
    async getCompanyInfo() {
      const res = await reqGetCompanyById(this.$store.state.user.UserInfo.companyId)
      this.companyForm = res.data
    },
    // 点击分配权限
    clickShowAssignDialog(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    // X按钮
    closeAssignDialog() {
      this.showAssignDialog = false
      this.$refs.tree.setCheckedKeys([])
    },
    // 分配权限弹窗 打开弹窗时的回调函数
    async openAssignDialog() {
      // 获取权限列表并且转换为树型结构
      const { data } = await reqGetPermissionList()
      this.permissionData = tranListToTreeData(data, '0')

      // 回显已有的角色权限
      const { data: { permIds }} = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async clickAssign() {
      const res = await reqAssignPerm({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success(res.message)
      this.closeAssignDialog()
    }
  }
}
</script>

<style scoped lang="scss">
#margin{
  margin: 15px 0;
}
</style>
